package dk.fungps;

import java.util.ArrayList;
import java.util.List;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;

import com.google.android.maps.GeoPoint;

public class GpsService extends Service {
	
	private LocalBinder mBinder = new LocalBinder();
	private List<Handler> mClients = new ArrayList<Handler>();
	private LocationManager mLocationManager;

	@Override
	public void onCreate() {
		super.onCreate();
        
        mLocationManager = 
        	(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
        mLocationManager.removeUpdates(mLocationListener);
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		mClients.remove(mClients.size() - 1);
		return super.onUnbind(intent);
	}
	
	@Override
	public IBinder onBind(Intent i) {
		return mBinder;
	}
	
	private LocationListener mLocationListener = new LocationListener() {
		
		@Override
		public void onStatusChanged(String s, int i, Bundle b) {
		}
		
		@Override
		public void onProviderEnabled(String s) {
		}
		
		@Override
		public void onProviderDisabled(String s) {
		}
		
		@Override
		public void onLocationChanged(Location l) {
			if(!mClients.isEmpty()) {
				
				if(l.getAccuracy() < 10) {
					
					// This will call the handle message of this handler on the GUI thread
					mClients.get(mClients.size() - 1).obtainMessage(0, l).sendToTarget();
				}
			}
		}
	};
	
	public class LocalBinder extends Binder {
		
		public GpsService bindActivity(Handler client) {
			mClients.add(client);
			return GpsService.this;
		}
	}

}
